package com.xiaoyg.algorithm.lru;

import java.util.HashMap;
import java.util.Map;

public class LRUCache {

    public Map<Integer, Node> map;

    public DoubleList cache;

    public int cap;

    public LRUCache(int capcity){
        this.cap = capcity;
        map = new HashMap<>();
        cache = new DoubleList();
    }

    public void makeRecently(int key){
        Node node = map.get(key);
        cache.remove(node);
        cache.addLast(node);
    }

    public int get(int key){
        //判断map中是否存在
        if(!map.containsKey(key)){
            return -1;
        }
        makeRecently(key);
        return map.get(key).val;
    }

    public void deleteKey(int key){
        Node node = map.get(key);
        cache.remove(node);
        map.remove(key);
        cap --;
    }

    public void removeLastRecently(){
        Node node = cache.removeFirst();
        map.remove(node.key);
        cap--;
    }

    public void addRecently(int key, int val){
        Node newNode = new Node(key, val);
        cache.addLast(newNode);
        //添加
        map.put(key, newNode);
        cap++;
    }

    public void put(int key,int val){
        //判断key是否存在
        if (map.containsKey(key)){
            deleteKey(key);
            addRecently(key,val);
            return;
        }

        if (cap == cache.size()){
            removeLastRecently();
        }
        //不存在，则创建node,然后塞到队首
        addRecently(key, val);
    }
}


